package org.ztr.yanai.blog.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.ztr.yanai.blog.utils.CorsProperties;

/**
 * @Author: ZhaoTR
 * @Date: Created in 2025/11/22 10:00
 * @Description: 跨域资源共享(CORS)配置类，支持多域名白名单和自定义请求头
 * @Version: 1.0
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    private final CorsProperties corsProperties;

    public CorsConfig(CorsProperties corsProperties) {
        this.corsProperties = corsProperties;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns(corsProperties.getAllowedOrigins().toArray(new String[0]))
                // 精确控制允许的方法
                .allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS")
                // 明确允许的请求头
                .allowedHeaders(
                        "Origin",
                        "Content-Type",
                        "Accept",
                        "Authorization",
                        "X-Requested-With",
                        "X-XSRF-TOKEN",
                        "x-request-id",
                        "apifoxtoken"
                )
                // 暴露响应头给客户端
                .exposedHeaders(
                        "Content-Disposition",
                        // 分页总数
                        "X-Total-Count",
                        // 当前页码
                        "X-Page-Number",
                        // 分页大小
                        "X-Page-Size"
                )
                // 允许携带凭证（cookies）
                .allowCredentials(true)
                // 预检请求缓存时间
                .maxAge(corsProperties.getMaxAge());
    }
}